﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;

namespace Qreed
{
    /// <summary>
    /// Based on a codeproject article: http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
    /// Provides methods for cloning objects.
    /// </summary>
    public static class CloneHelper
    {
        /// <summary>
        /// Creates a copy of the object by using binary serialization.
        /// </summary>
        /// <typeparam name="T">The type of object being copied.</typeparam>
        /// <param name="source">The object instance to copy.</param>
        /// <returns>The copied object.</returns>
        /// <seealso cref="CloneViaXml"/>
        public static T Clone<T>(T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            // Don't serialize a null object, simply return the default for that object
            if (Object.ReferenceEquals(source, null))
            {
                return default(T);
            }

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }

        /// <summary>
        /// Creates a copy of the object via an XML serializer.
        /// </summary>
        /// <typeparam name="T">The type of object being copied.</typeparam>
        /// <param name="source">The object instance to copy.</param>
        /// <returns>The copied object.</returns>
        /// <seealso cref="Clone"/>
        public static T CloneViaXml<T>(T source)
        {
            StringBuilder sb = new StringBuilder();
            Type type = typeof(T);

            XmlSerializer xmlSerializer = new XmlSerializer(type);

            using (StringWriter sw = new StringWriter(sb))
            {
                xmlSerializer.Serialize(sw, source);
            }

            using (StringReader sr = new StringReader(sb.ToString()))
            {
                return (T)xmlSerializer.Deserialize(sr);
            }
        }
    }

}
